import "./App.css";
import { useState } from "react";
import List from "./List";
const data = [
  {
    category: "Sporting Goods",
    price: "$49.99",
    stocked: true,
    name: "Football",
  },
  {
    category: "Sporting Goods",
    price: "$9.99",
    stocked: true,
    name: "Baseball",
  },
  {
    category: "Sporting Goods",
    price: "$29.99",
    stocked: false,
    name: "Basketball",
  },
  {
    category: "Electronics",
    price: "$99.99",
    stocked: true,
    name: "iPod Touch",
  },
  {
    category: "Electronics",
    price: "$399.99",
    stocked: false,
    name: "iPhone 5",
  },
  {
    category: "Electronics",
    price: "$199.99",
    stocked: true,
    name: "Nexus 7",
  },
];
const kind = Array.from(new Set([...data.map((item) => item.category)]));
console.log(kind);
function App() {
  const [formData, setFromData] = useState({
    isInput: "",
    isChecked: false,
  });
  const [showData, setShowData] = useState(data);

  const handleChange = (e) => {
    let val = e.target.name === "isInput" ? e.target.value : e.target.checked;
    console.log(val);

    setFromData({
      ...formData,
      [e.target.name]: val,
    });
    if (e.target.name === "isChecked") {
      if (val) {
        setShowData(
          data.filter(
            (item) =>
              item.name.includes(formData.isInput) && item.stocked === true
          )
        );
      } else {
        setShowData(
          data.filter((item) => item.name.includes(formData.isInput))
        );
      }
    }
    if (e.target.name === "isInput") {
      if (formData.isChecked) {
        setShowData(
          data.filter(
            (item) => item.name.includes(val) && item.stocked === true
          )
        );
      } else {
        setShowData(data.filter((item) => item.name.includes(val)));
      }
    }
  };
  return (
    <div className="App">
      <form>
        <label>
          <input
            name="isInput"
            value={formData.isInput}
            onChange={handleChange}
          />
        </label>
        <br />
        <label>
          <input name="isChecked" type="checkbox" onChange={handleChange} />
          <span>Only show products in stock</span>
        </label>
      </form>
      <div
        style={{
          display: "flex",
          width: "100px",
          margin: "0 auto",
          justifyContent: "space-between",
        }}
      >
        <div>Name</div>
        <div>Price</div>
      </div>

      {kind.map((item) => (
        <div key={item}>
          <h3>{item}</h3>
          {showData
            .filter((item3) => item3.category === item)
            .map((item2) => (
              <List key={item2.name}>
                <div style={{ color: item2.stocked ? "" : "red" }}>
                  {item2.name}
                </div>
                <div>{item2.price}</div>
              </List>
            ))}
        </div>
      ))}
    </div>
  );
}

export default App;
